let app = getApp();
let location = require("../../../mybehaviors/location/location");
Page({
  behaviors: [location],
  /**
   * 页面的初始数据
   */
  data: {
    locationStatus:false, //定位开关
    couponName: '',
    beginStatus:0,
    storeName: '',
    storeDetail:{},
    goodsId:0,
    addressDetail:'', //地址信息
    imageRight:false,
    favorite: false, //收藏开关
    shareShow: false, //打开分享弹窗
    posterImg:'', //海报信息
    posterShow: false,
    goodsDetails:{},
    goodsPlugin:{}, //原有的详情数据
    goodsBanner:'',
    couponStoreGoods:{},
    getGoods:{},
    fightGroupsId:0, //是否开团，0未开团
    pluginSetting:{},
    //客服插件
    customerOpen: false, //客服弹窗开关
    serviceShow: false,
    serviceQRcode: '',
    serviceMobile: '',
    cservice: '',
    storeListByGoods:[],
    longitude:'',
    latitude:'',
    activity_id:"",
    discountWidth:0,
    total:0

  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    if((options.goodsId??'') !== '') {
      this.setData({
        goodsId: parseInt(options.goodsId)
      })
      this.getGoodsDetails(this.data.goodsId);
    }
    this.goodsPoster();
    try {
      wx.removeStorageSync('applyaddresspoint');
    } catch (e) {
      // Do something when catch error
    }
    this._getLocation((mapdata, e) => {
      this.setData({
        longitude: e.lng,
        latitude: e.lat
      });
      this.getStoreListByGoods();
    },(error) => {
      this.setData({locationStatus: error});
    });
    this.serviceDetail();
    
  },
  onReady() {
    
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    try {
      let value = wx.getStorageSync('applyaddresspoint');
      if (value) {
        this.setData({
          longitude: value.point.lng,
          latitude: value.point.lat,
          locationStatus:true
        });
        // Do something with return value
      } else {
        this._getLocation((mapdata, e) => {
          this.setData({
            longitude: e.lng,
            latitude: e.lat,
            locationStatus:true
          });
          this.getStoreListByGoods();
        },(error) => {
          this.setData({locationStatus: error});
        });
      }
    } catch (e) {
      console.log(e);
    }
    wx.showShareMenu({
      withShareTicket: false,
      menus: ["shareAppMessage", "shareTimeline"],
    });
    
  },
  getStoreListByGoods() { //商品可用商户列表 
    let urlStr = app.getNetAddresss("plugin.coupon-store.frontend.store.getStoreListByGoods");
    let json = {
      goods_id:this.data.goodsId,
      store_name: '',
      longitude: this.data.longitude,
      latitude: this.data.latitude
    };
    app._postNetWork({
      url: urlStr,
      data:json,
      success:  (resdata) => {
        let res = resdata.data;
        if (res.result == 1) {
          let storeaddress = res.data.data;
          let addressDetail = `${storeaddress[0].city}${storeaddress[0].district}${storeaddress[0].street}${storeaddress[0].address}`;
          this.setData({
            addressDetail: addressDetail,
            storeListByGoods: res.data.data,
            total:res.data.total
          })
        } else {
          wx.showToast({
            icon: 'none',
            title: res.msg,
            duration: 1500
          });
        }
      },
      fail: function (res) {
        console.log(res);
      }
    });
  },
  getGoodsDetails(id) {
    let urlStr = app.getNetAddresss("goods.goods.get-goods-page");
    let json = {
      id: Number(id),
      basic_info: 1
    };
    app._postNetWork({
      url: urlStr,
      data: json,
      success: (resdata) => {
        let res = resdata.data;
        let couponStoreGoods = res.data.plugin?.coupon_store_goods;
        let startTime = couponStoreGoods.start_time * 1000;
        let endTime = couponStoreGoods.end_time * 1000;
        let nowtime = new Date().getTime();
        let beginStatus = 0;
        if(startTime > nowtime) {
          beginStatus = 0;
        } else if(nowtime >= startTime && nowtime < endTime) {
          beginStatus = 1;
        } else {
          beginStatus = 2;
        }
        if (res.result == 1) {
          this.setData({
            goodsBanner:res.data.get_goods.thumb,
            fightGroupsId:res.data.plugin.coupon_store_goods?.fight_groups_id,
            couponStoreGoods:res.data.plugin?.coupon_store_goods,
            getGoods:res.data.get_goods,
            goodsPlugin: res.data.plugin,
            beginStatus: beginStatus,
            pluginSetting: res.basic_info?.plugin_setting?.coupon_store,
            favorite:res.data.is_favorite?.status?true:false
          })
          let query = this.createSelectorQuery();  //根据价格的长度修改样式
          let that = this;
          query.select('#goods-price').boundingClientRect()
            query.exec(function (res) {
              //res就是 所有标签为publicImg的元素的信息 的数组
              that.setData({
                discountWidth: res[0].width
              })
          });
        }
       
      },
    });
  },
  toGroupCode() { //群活码跳转功能
    if(this.data.goodsPlugin.group_code.jump_mode === 'home') {
      wx.reLaunch({
        url: '/packageE/groupCode/groupCode',
      });
    }else if(this.data.goodsPlugin.group_code.code_mini_url){
      wx.navigateTo({
        url: this.data.goodsPlugin.group_code.code_mini_url
      });
    }
  },
  shopNavTo() {
    wx.navigateTo({
      url: `/packageF/consumption/shopList/shopList?goodsId=${this.data.goodsId}&storeName=${this.data.storeDetail.store_name}&longitude=${this.data.longitude}&latitude=${this.data.latitude}`
    })
  },
  locationOn() { //定位功能
    let userLocationFlag = this.checkAlbum("scope.userLocation");
    if (!userLocationFlag) {
      return app.tips("获取位置失败，请重新进入后授权");
    }
  },
  async checkAlbum(scopeName) {
    let writePhotosAlbum = await this.getAuthSetting(scopeName);
    return new Promise((resolve, reject) => {
      if (!writePhotosAlbum) {
        wx.showModal({
          title: "请开启授权",
          content: "是否跳转设置页开启授权",
          success(res) {
            if (res.confirm) {
              wx.openSetting({
                success(settingdata) {
                  if (settingdata.authSetting[scopeName]) {
                    resolve(true);
                  } else {
                    resolve(false);
                  }
                },
              });
            } else if (res.cancel) {
              resolve(false);
            }
          },
          fail: () => {
            resolve(false);
          },
        });
      } else resolve(true);
    });
  },
  getAuthSetting(authName) {
    return new Promise((resolve, reject) => {
      wx.getSetting({
        success(res) {
          if (!res.authSetting[authName]) {
            wx.authorize({
              scope: authName,
              success() {
                resolve(true);
              },
              fail() {
                resolve(false);
              },
            });
          } else resolve(true);
        },
        fail() {
          resolve(false);
        },
      });
    });
  },
  onPreorder() { //跳转预下单
    if(this.data.getGoods.show_stock === 0) {
      wx.showToast({
        icon: 'none',
        title: '商品没有库存了',
        duration: 1500
      });
      return;
    }
    wx.navigateTo({
      url: `/packageF/consumption/orderAffirm/orderAffirm?goodsId=${this.data.goodsId}&optionsId=&total=1`
    })
  },
  goodsGroup() {
    if(this.data.getGoods.show_stock === 0) {
      wx.showToast({
        icon: 'none',
        title: '商品没有库存了',
        duration: 1500
      });
      return;
    }
    wx.navigateTo({
      url: `/packageA/detail_v2/detail_v2?id=${this.data.couponStoreGoods.fight_groups_id}&name=group`
    })
  },
  //添加收藏
  onFavorite() {
    let that = this;
    let urlStr = '';
    let favorite = !this.data.favorite;
    if(favorite) {
      urlStr = app.getNetAddresss("member.member-favorite.store");
    } else {
      urlStr = app.getNetAddresss("member.member-favorite.destroy");
    }
    urlStr += "&goods_id=" + this.data.goodsId;
    app._getNetWork({
      url: urlStr,
      success: function (resdata) {
        var res = resdata.data;
        that.setData({
          favorite: favorite,
        });
        if (res.result == 1) {
          wx.showToast({
            icon: "none",
            title: res.msg,
            duration: 3000,
          });
        } else {
          wx.showToast({
            icon: "none",
            title: res.msg,
            duration: 3000,
          });
        }
      },
      fail: function (res) {
        console.log(res);
      },
    });
  },
  shareHint() {
    wx.showToast({
      icon: "none",
      title: '长按图片分享好友',
      duration: 3000,
    });
  },
  goodsPoster() { //海报信息设置
    let that = this;
    let urlStr = app.getNetAddresss("plugin.coupon-store.frontend.poster.goodsPoster");
    let json = {
      goods_id: this.data.goodsId,
    };
    app._postNetWork({
      url: urlStr,
      data:json,
      success: function (resdata) {
        let res = resdata.data;
        if (res.result == 1) {
          that.setData({
            posterImg:res.data.url
          })
        } else {
          wx.showToast({
            icon: 'none',
            title: res.msg,
            duration: 1500
          });
        }
      },
      fail: function (res) {
        console.log(res);
      }
    });
  },
  tapIndex() { //首页跳转
    wx.redirectTo({
      url: '/packageG/index/index',
    })
  },
  gotoChat(evt) { //客服跳转
    console.log(evt);
    let url = evt.currentTarget.dataset.cservice + "&goods_id=" + this.data.goodsId;
    wx.navigateTo({
      url: url,
      fail: (err) => {
        app.tips("客服路由出错");
      }
    });
  },
  serviceDetail() {  //客服插件开关
    let goods_id = this.data.goodsId;
    let urlStr = app.getNetAddresss("goods.customer-service.index");
    app._postNetWork({
      url: urlStr,
      data: {
        goods_id: goods_id,
      },
      success: (resdata) => {
        var res = resdata.data;
        if (res.result == 1) {
          this.setData({
            customerOpen:res.data.customer_open,
            showKefu: true,
            cservice: res.data.cservice,
            serviceQRcode: res.data.service_QRcode,
            serviceMobile: res.data.service_mobile,
          });
          console.log(this.data.cservice);
        }
      },
      fail: function (res) {
        console.log(res);
      },
    });
  },
  saveImg() {
    wx.getSetting({
      success(res) {
        if (!res.authSetting['scope.writePhotosAlbum']) {
          wx.authorize({
            scope: 'scope.writePhotosAlbum',
            success() {
              console.log('授权成功');
            }
          });
        }
      }
    });
    var imgSrc = this.data.posterImg;
    wx.downloadFile({
      url: imgSrc,
      success: function (res) {
        //图片保存到本地
        wx.saveImageToPhotosAlbum({
          filePath: res.tempFilePath,
          success: function (data) {
            wx.showToast({
              title: '保存成功',
              icon: 'none',
              duration: 2000
            });
          },
          fail: function (err) {
            if (err.errMsg === "saveImageToPhotosAlbum:fail auth deny") {
              console.log("当初用户拒绝，再次发起授权");
              wx.openSetting({
                success(settingdata) {
                  if (settingdata.authSetting['scope.writePhotosAlbum']) {
                    wx.showToast({
                      icon: 'none',
                      title: '获取权限成功,再次长按保存图片',
                      duration: 1500
                    });
                  } else {
                    wx.showToast({
                      icon: 'none',
                      title: '获取权限失败,保存图片需要用户授权',
                      duration: 1500
                    });
                  }
                }
              });
            }
          },
          complete(res) {
            console.log(res);
          }
        });
      }
    });
  },
  showPop() {
    console.log('12342');
    let setServicePlugin = app._isTextEmpty(this.data.serviceQRcode) && app._isTextEmpty(this.data.serviceMobile);
    if (app._isTextEmpty(this.data.cservice) && setServicePlugin) {
      return app.tips("抱歉，暂未设置客服信息");
    }
    if (!app._isTextEmpty(this.data.cservice) && setServicePlugin) {
      this.gotoChat({
        currentTarget: {
          dataset: {
            cservice: this.data.cservice
          }
        }
      }) //只设置了客服链接，直接跳转
      return;
    }
    this.setData({
      serviceShow: true,
    });
  },
  
  sharePopup() {
    this.setData({
      shareShow: true,
    });
  },
  closePop() {
    this.setData({
      serviceShow: false,
    });
  },
  PosterClose() {
    this.setData({
      posterShow: false,
    });
  },
  shareClose() {
    this.setData({
      shareShow: false,
    });
  },
  PosterPopup() {
    this.setData({
      posterShow: true,
    });
  },
  callPhone() {
    wx.makePhoneCall({
      phoneNumber: this.data.serviceMobile
    });
  },
  callStore() {
    wx.makePhoneCall({
      phoneNumber: this.data.storeListByGoods[0].store_mobile
    });
  },
  copyWriting() {
    wx.navigateTo({
      url: '/packageF/consumption/copyWriting/copyWriting?goodsId=' + this.data.goodsId
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },
  onShareTimeline() {
    return {
      title: this.data.getGoods.title,
      query: `/packageF/consumption/goodsDetails/goodsDetails?goodsId=${this.data.goodsId}`,
      imageUrl: this.data.goodsBanner
    }
  },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {
    let shareConfig = {
      title: this.data.getGoods.title,
      path: `/packageF/consumption/goodsDetails/goodsDetails?goodsId=${this.data.goodsId}`,
      imageUrl: this.data.goodsBanner
    }
    return {
      title: shareConfig.title,
      path: shareConfig.path,
      imageUrl: shareConfig.imgUrl
    };

  }
})